import time
import win32gui, win32ui, win32con, win32api
from PIL import Image, ImageGrab
import numpy as np
def get_window_pos(name):
    name = name
    handle = win32gui.FindWindow(0, name)
    # 获取窗口句柄

    if handle == 0:
        return None
    else:
        rect = win32gui.GetWindowRect(handle)
        if rect[0] < 0:
            win32gui.ShowWindow(handle, win32con.SW_SHOWNORMAL)
            rect = win32gui.GetWindowRect(handle)
        win32gui.SetForegroundWindow(handle)
        return rect

def window_capture(filename, rect):
    hwnd = 0 # 窗口的编号，0号表示当前活跃窗口
    # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息

    w = rect[2] - rect[0]
    h = rect[3] - rect[1]
    saveBitMap.CreateCompatibleBitmap(mfcDC,w, h)
    # 高度saveDC，将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角（0，0）长宽为（w，h）的图片
    saveDC.BitBlt((rect[0], rect[1]), (rect[2], rect[3]), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)

import os
from PIL import Image

def print_img(img, w=18, h=18):
    img_array = np.array(img)
    for i in range(h):
        for j in range(w):
            print(i, " ", j, " ", img_array[i][j], end= "  ")

        print("\n")


def splitimage(src, rownum, colnum, dstpath):
    img = Image.open(src)
    w, h = img.size
    if rownum <= h and colnum <= w:
        print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
        print('开始处理图片切割, 请稍候...')

        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
        basename = fn[0]
        ext = fn[-1]

        num = 0
        rowheight = 18
        colwidth = 18
        a = 38
        b = 81
        x0 = 38
        y0 = 80
        for r in range(rownum):
            for c in range(colnum):
                box = (c * colwidth + x0, r * rowheight + y0, (c + 1) * colwidth  + x0, (r + 1) * rowheight + y0)
                img2 = img.crop(box)
                img2.save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), ext)
                num = num + 1
                print('Pic No. = ', num)
                print_img(img2)


        print('图片切割完毕，共生成 %s 张小图片。' % num)
    else:
        print('不合法的行列切割参数！')




if __name__ == '__main__':

    pic = 'h1.bmp'
    beg = time.time()
    rect = get_window_pos('扫雷')
    print(rect)
    img_ready = ImageGrab.grab(rect)
    # window_capture('h.jpg', rect)
    # img_ready.show()
    img_ready.save(fp=pic)
    end = time.time()
    print(end - beg)

    src = pic
    if os.path.isfile(src):
        # dstpath = input('请输入图片输出目录（不输入路径则表示使用源图片所在目录）：')
        dstpath = ''
        if (dstpath == '') or os.path.exists(dstpath):
            row = 9
            col = 9
            if row > 0 and col > 0:
                splitimage(src, row, col, dstpath)
            else:
                print('无效的行列切割参数！')
        else:
            print('图片输出目录 %s 不存在！' % dstpath)
    else:
        print('图片文件 %s 不存在！' % src)
